import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient();

async function hashPassword(password: string): Promise<string> {
  return bcrypt.hash(password, 12);
}

async function initAdmin() {
  try {
    console.log('开始初始化管理员账号...');

    // 检查是否已有超级管理员
    const existingAdmin = await prisma.user.findFirst({
      where: {
        role: 1, // 1-超级管理员
      },
    });
    
    if (existingAdmin) {
      console.log('超级管理员账号已存在，跳过初始化');
    } else {
      // 创建默认超级管理员
      const hashedPassword = await hashPassword('Xx@123456');
      
      await prisma.user.create({
        data: {
          username: 'admin',
          email: 'admin@zufe.edu.cn',
          password: hashedPassword,
          nickname: '系统管理员',
          role: 1, // 1-超级管理员
          status: 1,
        },
      });

      console.log('✅ 管理员账号初始化成功！');
      console.log('用户名: admin');
      console.log('邮箱: admin@zufe.edu.cn');
      console.log('密码: Xx@123456');
      console.log('⚠️  请在首次登录后立即修改密码！');
    }
    
  } catch (error) {
    console.error('❌ 初始化管理员账号失败:', error);
  } 
}

async function initData() {
  try {
    console.log('开始初始化菜单和分类数据...');


    // 创建“网址提交”菜单
    await prisma.menu.upsert({
      where: { id: 'submit_site' },
      update: {},
      create: {
        id: 'submit_site',
        name: '网址提交',
        path: '/submit',
        parentId: null,
      },
    });

    // 创建“关于我们”菜单
    await prisma.menu.upsert({
      where: { id: 'about_us' },
      update: {},
      create: {
        id: 'about_us',
        name: '关于我们',
        path: '/about',
        parentId: null,
      },
    });

    // 创建“热门资讯”菜单
    const hotNewsMenu = await prisma.menu.upsert({
      where: { id: 'hot_news' },
      update: {},
      create: {
        id: 'hot_news',
        name: '热门资讯',
        path: '/news',
        sysCode: 'hot_news',
      },
    });

    // 为“热门资讯”创建分类
    const techNewsCategory = await prisma.category.upsert({
      where: { id: 'tech_news' },
      update: {},
      create: {
        id: 'tech_news',
        name: '科技动态',
        menuId: hotNewsMenu.id,
      },
    });

    const industryTrendsCategory = await prisma.category.upsert({
      where: { id: 'industry_trends' },
      update: {},
      create: {
        id: 'industry_trends',
        name: '行业趋势',
        menuId: hotNewsMenu.id,
      },
    });

    // 为“科技动态”分类添加内容
    const techNewsContents = [
      {
        title: 'GPT-4o 发布：更快、更强、更免费',
        content: 'OpenAI 发布了其最新的旗舰模型 GPT-4o，它在速度、功能和成本效益方面都带来了显著提升。',
        type: 3, // 3-资讯
      },
    ];

    for (const contentData of techNewsContents) {
      const newContent = await prisma.content.create({
        data: {
          title: contentData.title,
          content: contentData.content,
          summary: contentData.content,
          type: contentData.type,
        },
      });
      await prisma.contentCategory.create({
        data: {
          contentId: newContent.id,
          categoryId: techNewsCategory.id,
        },
      });
    }

    // 创建“凯笙导航”菜单
    const kasonNav = await prisma.menu.upsert({
      where: { id: 'kason_nav' },
      update: {},
      create: {
        id: 'kason_nav',
        name: '凯笙导航',
        path: '/kason-nav',
        sysCode: 'kason_nav',
      },
    });

    // 为“凯笙导航”创建分类
    const popularSitesCategory = await prisma.category.upsert({
      where: { id: 'kason_nav_popular_sites' },
      update: {},
      create: {
        id: 'kason_nav_popular_sites',
        name: '常用网站',
        menuId: kasonNav.id,
      },
    });

    // 为“常用网站”分类添加内容
    const kasonNavContents = [
      {
        title: 'Google',
        url: 'https://www.google.com',
        type: 1,
      },
      {
        title: 'GitHub',
        url: 'https://github.com',
        type: 1,
      },
    ];

    for (const contentData of kasonNavContents) {
      const newContent = await prisma.content.create({
        data: {
          title: contentData.title,
          url: contentData.url,
          type: contentData.type,
        },
      });
      await prisma.contentCategory.create({
        data: {
          contentId: newContent.id,
          categoryId: popularSitesCategory.id,
        },
      });
    }

    // 创建“AI工具导航”菜单
    const aiToolsNav = await prisma.menu.upsert({
      where: { id: 'ai_tools_nav' },
      update: {},
      create: {
        id: 'ai_tools_nav',
        name: 'AI工具导航',
        path: '/ai-tools',
        sysCode: 'ai_tools_nav',
      },
    });

    // 为“AI工具导航”创建分类
    const copywritingCategory = await prisma.category.upsert({
      where: { id: 'ai_tools_copywriting' },
      update: {},
      create: {
        id: 'ai_tools_copywriting',
        name: '文案写作',
        menuId: aiToolsNav.id,
      },
    });



    // 为“文案写作”分类添加内容
    const copywritingContents = [
      {
        title: 'Notion AI',
        content: '强大的笔记和协作工具，集成了AI写作助手。',
        url: 'https://www.notion.so/product/ai',
        type: 2, // 2-智能体
      },
      {
        title: 'Jasper',
        content: '领先的AI内容生成平台，用于营销、博客等。',
        url: 'https://www.jasper.ai/',
        type: 2,
      },
    ];

    for (const contentData of copywritingContents) {
      const secretKey = `${contentData.title.toLowerCase().replace(/\s/g, '-')}-secret`;
      let agent = await prisma.agent.findFirst({ where: { secretKey } });

      if (agent) {
        agent = await prisma.agent.update({
          where: { id: agent.id },
          data: {
            welcomeText: `欢迎使用 ${contentData.title}，有什么可以帮助你的吗？`,
            canUploadImg: 1,
            canUploadDoc: 0,
          },
        });
      } else {
        agent = await prisma.agent.create({
          data: {
            name: contentData.title,
            secretKey,
            welcomeText: `欢迎使用 ${contentData.title}，有什么可以帮助你的吗？`,
            canUploadImg: 1,
            canUploadDoc: 0,
          },
        });
      }

      const newContent = await prisma.content.create({
        data: {
          title: contentData.title,
          content: contentData.content,
          summary: contentData.content,
          url: contentData.url,
          type: contentData.type,
          agentId: agent.id,
        },
      });
      await prisma.contentCategory.create({
        data: {
          contentId: newContent.id,
          categoryId: copywritingCategory.id,
        },
      });
    }

    // 为“代码生成”分类添加内容
    const codeGenerationContents = [
      {
        title: 'GitHub Copilot',
        content: '你的AI配对程序员，帮助你更快地编写代码。',
        url: 'https://github.com/features/copilot',
        type: 2,
      },
    ];

    for (const contentData of codeGenerationContents) {
      const secretKey = `${contentData.title.toLowerCase().replace(/\s/g, '-')}-secret`;
      let agent = await prisma.agent.findFirst({ where: { secretKey } });

      if (agent) {
        agent = await prisma.agent.update({
          where: { id: agent.id },
          data: {
            welcomeText: `欢迎使用 ${contentData.title}，有什么可以帮助你的吗？`,
            canUploadImg: 1,
            canUploadDoc: 1,
          },
        });
      } else {
        agent = await prisma.agent.create({
          data: {
            name: contentData.title,
            secretKey,
            welcomeText: `欢迎使用 ${contentData.title}，有什么可以帮助你的吗？`,
            canUploadImg: 1,
            canUploadDoc: 1,
          },
        });
      }

      const newContent = await prisma.content.create({
        data: {
          title: contentData.title,
          content: contentData.content,
          summary: contentData.content,
          url: contentData.url,
          type: contentData.type,
          agentId: agent.id,
        },
      });

    }

    console.log('✅ 菜单和分类数据初始化成功！');

  } catch (error) {
    console.error('❌ 初始化菜单和分类数据失败:', error);
  }
}

async function main() {
  await initAdmin();
  await initData();
  await prisma.$disconnect();
}

main();